package service

import (
	"context"

	commonConstant "algo-sdk-go/common/constant"
	commonTools "algo-sdk-go/common/tools"
	commonCache "algo-sdk-go/framework/middleware/cache"
	"algo-sdk-go/project/matchmaking/adapter/cache"
	"algo-sdk-go/project/matchmaking/common/constant"

	"github.com/pkg/errors"
)

type LoginService struct {
	cache *cache.MatchMakingLocalCache
}

func NewLoginService(cache *cache.MatchMakingLocalCache) *LoginService {
	return &LoginService{
		cache: cache,
	}
}

func (l *LoginService) LoadLocalCacheResult(ctx context.Context, symbol string, cacheFlush bool, expireTime int) (int, error) {
	var (
		cacheParam = &commonCache.CacheWare{
			Ctx:        ctx,
			PrefixKey:  constant.LoginLocalCachePrefix,
			IdList:     []string{symbol},
			CacheType:  commonConstant.LocalCacheType,
			LocalCache: (*commonCache.LocalCache)(l.cache),
			ExpireTime: expireTime,
			CacheFlush: cacheFlush,
		}
		produceFlag = func(context.Context, []string) ([]int, error) {
			return []int{commonTools.ReduceRand()}, nil
		}
	)

	result, err := commonCache.GetCacheData(cacheParam, produceFlag, commonTools.IntCast, nil, func(int) string { return symbol })
	if err != nil {
		return -1, errors.WithMessage(err, "LoadSymbolCache_GetCacheData_err")
	}

	return commonTools.First(result), nil
}
